package com.gmall.console.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gmall.console.system.entity.Role;
import com.gmall.console.system.entity.RoleMenu;
import com.gmall.console.system.mapper.RoleMapper;
import com.gmall.console.system.mapper.RoleMenuMapper;
import com.gmall.console.system.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Jone
 * @since 2024-05-29
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    @Transactional
    public void addRole(Role role) {

        this.baseMapper.insert(role);

        List<Integer> menuIdList = role.getMenuIdList();

        if(null != menuIdList){
            for (Integer menuId : menuIdList) {
                roleMenuMapper.insert(new RoleMenu(null,role.getId(),menuId));
            }
        }

    }

    @Override
    public Role getRoleInfo(String id) {

        Role role = this.baseMapper.selectById(id);
        List<Integer> menuId = roleMenuMapper.getMenuId(id);
        role.setMenuIdList(menuId);
        return role;
    }

    @Override
    @Transactional
    public void updateRole(Role role) {

        //先删除后添加
        this.baseMapper.updateById(role);
        LambdaQueryWrapper<RoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenu::getRoleId,role.getId());
        roleMenuMapper.delete(wrapper);

        //新增
        if(null != role.getMenuIdList()){
            for (Integer menuId : role.getMenuIdList()) {
                roleMenuMapper.insert(new RoleMenu(null,role.getId(),menuId));
            }
        }

    }
}
